package ch10.gongju;

import ch10.Date.UserDao;
import ch10.UserBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);

    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        UserDao userDao = new UserDao();
        //获得当前登录用户的信息
        UserBean userBean = (UserBean)request.getSession().getAttribute('user');
        Integer createdBy = userBean.getId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //1.获取请求参数，封装到UserBean
        Date birthday = null;
        try {
            birthday =sdf.parse(request.getParameter("birthday"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        UserBean tmp = new UserBean();
        Date creationDate = new Date();
        tmp.setUserName(request.getParameter("userName"));
//        userBean.setId(rst2.getInt("id"));
        tmp.setUserCode(request.getParameter("userCode"));
//        tmp.setUserName(rst2.getString("userName"));
        tmp.setUserPassword(request.getParameter("userPassword"));
        tmp.setGender(Integer.parseInt(request.getParameter("gender")));
        tmp.setBirthday("birthday");
        tmp.setPhone(request.getParameter("phone"));
        tmp.setAddress(request.getParameter("address"));
        tmp.setUserRole(Integer.parseInt(request.getParameter("userRole")));
        tmp.setCreationDate(creationDate);
        tmp.setCreatedBy(createdBy);
        //2.调用Dao,完成注册
        Integer result = userDao.addUser(tmp);
        if (result > 0){
            //3.注册成功，跳转
            response.sendRedirect("/login.jsp");
        }else{
            //4.注册失败，回到注册页面
            request.setAttribute("msg","注册失败");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }
}
